import { showToast, showLoadingToast, closeToast } from "vant";
// 支持的视频扩展名列表
const VIDEO_EXTENSIONS = [".mp4", ".webm", ".mov", ".avi", ".mkv", ".flv"];

// 封装视频下载工具
export const downloadVideo = {
  /**
   * 下载视频文件
   * @param url 视频地址 (需确保支持CORS)
   * @param fileName 保存的文件名 (带扩展名)
   * @param timeout 超时时间（毫秒，默认30秒）
   */
  async download(
    url: string,
    fileName: string = `video_${Date.now()}`,
    timeout: number = 30000
  ): Promise<void> {
    // 处理文件名扩展名
    const finalFileName = this.resolveFileName(fileName, url);

    // 显示加载提示
    const toast = showLoadingToast({
      message: "视频下载中...",
      forbidClick: true,
      duration: 0
    });

    try {
      // 设置超时取消
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), timeout);

      // 发起带进度的fetch请求
      const response = await fetch(url, {
        signal: controller.signal,
        headers: new Headers({ Origin: location.origin }),
        mode: "cors"
      });
      clearTimeout(timer);

      if (!response.ok) {
        throw new Error(`下载失败: ${response.status} ${response.statusText}`);
      }
      if (!response.body) throw new Error("无效的视频流");

      // 获取内容长度
      const contentLength = response.headers.get("content-length");
      const total = parseInt(contentLength || "0", 10);

      // 创建读取流
      const reader = response.body.getReader();
      let received = 0;
      const chunks: Uint8Array[] = [];

      // 读取数据
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        chunks.push(value);
        received += value.length;

        // 更新进度提示
        if (total > 0) {
          const progress = Math.floor((received / total) * 100);
          toast.message = `下载中 ${progress}%`;
        }
      }

      // 合并数据
      const blob = new Blob(chunks);
      this.saveFile(blob, finalFileName);

      // 显示成功提示
      closeToast();
      showToast({
        message: "视频下载成功",
        type: "success",
        duration: 2000
      });
    } catch (error: any) {
      closeToast();
      showToast({
        message: `下载失败: ${error.message || error}`,
        type: "fail",
        duration: 3000
      });
      throw error;
    }
  },
  /**
   * 智能解析文件名扩展名
   * @param fileName 传入的文件名
   * @param url 视频URL
   * @returns 带正确扩展名的文件名
   */
  resolveFileName(fileName: string, url: string): string {
    // 如果文件名已有扩展名，直接返回
    if (this.hasVideoExtension(fileName)) {
      return fileName;
    }

    // 尝试从URL中提取扩展名
    const urlExt = this.extractExtensionFromUrl(url);
    if (urlExt) {
      return `${fileName}${urlExt}`;
    }

    // 默认使用.mp4
    return `${fileName}.mp4`;
  },

  /**
   * 检查字符串是否包含视频扩展名
   * @param str 文件名或URL
   */
  hasVideoExtension(str: string): boolean {
    const lowerStr = str.toLowerCase();
    return VIDEO_EXTENSIONS.some(ext => lowerStr.endsWith(ext));
  },

  /**
   * 从URL中提取视频扩展名
   * @param url 视频URL
   * @returns 扩展名或空字符串
   */
  extractExtensionFromUrl(url: string): string | null {
    try {
      // 去除查询参数和哈希
      const cleanUrl = url.split("?")[0].split("#")[0];

      // 获取最后一个点后面的部分
      const lastDotIndex = cleanUrl.lastIndexOf(".");
      if (lastDotIndex === -1) return null;

      const extension = cleanUrl.slice(lastDotIndex);
      return this.hasVideoExtension(extension) ? extension : null;
    } catch {
      return null;
    }
  },

  // 保存文件到本地
  saveFile(blob: Blob, fileName: string) {
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.style.display = "none";

    document.body.appendChild(link);
    link.click();

    // 清理资源
    setTimeout(() => {
      URL.revokeObjectURL(link.href);
      document.body.removeChild(link);
    }, 100);
  }
};
